import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import { templateService } from '@/services/template.service';
import { message } from 'antd';

interface Template {
  id: string;
  name: string;
  description?: string;
  category: string;
  content: string;
  prompt?: string;
  variables: TemplateVariable[];
  tags?: string[];
  isPublic?: boolean;
  language?: string;
  usageCount: number;
  createdAt: string;
  updatedAt?: string;
  authorId?: string;
  lastUsedAt?: string;
}

interface TemplateVariable {
  name: string;
  description: string;
  type: 'text' | 'number' | 'date' | 'select' | 'textarea';
  required: boolean;
  defaultValue?: string;
  options?: string[];
  placeholder?: string;
}

interface TemplateStore {
  // 状态
  templates: Template[];
  myTemplates: Template[];
  publicTemplates: Template[];
  favoriteTemplates: string[];
  recentTemplates: string[];
  loading: boolean;
  error: string | null;
  searchQuery: string;
  selectedCategory: string;
  
  // 操作
  loadTemplates: () => Promise<void>;
  loadMyTemplates: () => Promise<void>;
  loadPublicTemplates: () => Promise<void>;
  searchTemplates: (query: string) => Promise<void>;
  getTemplateById: (id: string) => Template | undefined;
  createTemplate: (template: Partial<Template>) => Promise<Template>;
  updateTemplate: (id: string, template: Partial<Template>) => Promise<void>;
  deleteTemplate: (id: string) => Promise<void>;
  duplicateTemplate: (id: string) => Promise<Template>;
  toggleFavorite: (templateId: string) => void;
  addToRecent: (templateId: string) => void;
  clearRecentTemplates: () => void;
  incrementUsageCount: (templateId: string) => void;
  importTemplate: (templateData: any) => Promise<Template>;
  exportTemplate: (templateId: string) => Promise<any>;
  applyTemplate: (templateId: string, variables: Record<string, any>) => string;
  setSearchQuery: (query: string) => void;
  setSelectedCategory: (category: string) => void;
}

// 默认模板数据
const DEFAULT_TEMPLATES: Template[] = [
  {
    id: 'default_news_1',
    name: '突发新闻报道模板',
    description: '适用于突发事件的快速新闻报道',
    category: 'news',
    content: `【{标题}】

{时间}，{地点}发生{事件描述}。

据{消息来源}消息，{详细情况}。目前，{现状描述}。

{相关部门}已经{采取措施}。{官方声明}。

{影响分析}。{后续安排}。

相关专家表示，{专家观点}。

（记者 {记者名} 报道）`,
    variables: [
      { name: '标题', description: '新闻标题', type: 'text', required: true },
      { name: '时间', description: '事件发生时间', type: 'text', required: true },
      { name: '地点', description: '事件发生地点', type: 'text', required: true },
      { name: '事件描述', description: '事件简要描述', type: 'textarea', required: true },
      { name: '消息来源', description: '消息来源机构', type: 'text', required: true },
      { name: '详细情况', description: '事件详细情况', type: 'textarea', required: true },
      { name: '现状描述', description: '当前状况', type: 'textarea', required: true },
      { name: '相关部门', description: '处理部门', type: 'text', required: true },
      { name: '采取措施', description: '已采取的措施', type: 'textarea', required: true },
      { name: '官方声明', description: '官方声明内容', type: 'textarea', required: false },
      { name: '影响分析', description: '事件影响分析', type: 'textarea', required: false },
      { name: '后续安排', description: '后续处理安排', type: 'textarea', required: false },
      { name: '专家观点', description: '专家评论', type: 'textarea', required: false },
      { name: '记者名', description: '记者署名', type: 'text', required: true }
    ],
    tags: ['新闻', '突发', '报道'],
    isPublic: true,
    language: 'zh',
    usageCount: 156,
    createdAt: '2024-01-01T00:00:00Z'
  },
  {
    id: 'default_product_1',
    name: '产品介绍模板',
    description: '用于新产品发布和介绍',
    category: 'product',
    content: `{产品名称} - {一句话介绍}

【产品概述】
{产品详细介绍}

【核心功能】
1. {功能1}：{功能1描述}
2. {功能2}：{功能2描述}
3. {功能3}：{功能3描述}

【产品优势】
• {优势1}
• {优势2}
• {优势3}

【应用场景】
{应用场景描述}

【目标用户】
{目标用户群体}

【技术规格】
{技术参数}

【价格信息】
{价格方案}

了解更多：{联系方式}`,
    variables: [
      { name: '产品名称', description: '产品名称', type: 'text', required: true },
      { name: '一句话介绍', description: '产品slogan', type: 'text', required: true },
      { name: '产品详细介绍', description: '产品详细介绍', type: 'textarea', required: true },
      { name: '功能1', description: '核心功能1', type: 'text', required: true },
      { name: '功能1描述', description: '功能1详细描述', type: 'textarea', required: true },
      { name: '功能2', description: '核心功能2', type: 'text', required: true },
      { name: '功能2描述', description: '功能2详细描述', type: 'textarea', required: true },
      { name: '功能3', description: '核心功能3', type: 'text', required: true },
      { name: '功能3描述', description: '功能3详细描述', type: 'textarea', required: true },
      { name: '优势1', description: '产品优势1', type: 'text', required: true },
      { name: '优势2', description: '产品优势2', type: 'text', required: true },
      { name: '优势3', description: '产品优势3', type: 'text', required: true },
      { name: '应用场景描述', description: '应用场景', type: 'textarea', required: true },
      { name: '目标用户群体', description: '目标用户', type: 'textarea', required: true },
      { name: '技术参数', description: '技术规格', type: 'textarea', required: false },
      { name: '价格方案', description: '价格信息', type: 'textarea', required: false },
      { name: '联系方式', description: '联系方式', type: 'text', required: true }
    ],
    tags: ['产品', '介绍', '营销'],
    isPublic: true,
    language: 'zh',
    usageCount: 89,
    createdAt: '2024-01-02T00:00:00Z'
  },
  {
    id: 'default_blog_1',
    name: '技术博客模板',
    description: '技术分享和教程文章模板',
    category: 'blog',
    content: `# {文章标题}

## 前言
{引言内容}

## {主题}是什么？
{概念介绍}

## 为什么需要{主题}？
{必要性说明}

## 如何使用{主题}？

### 步骤1：{步骤1标题}
{步骤1内容}

\`\`\`{代码语言}
{示例代码1}
\`\`\`

### 步骤2：{步骤2标题}
{步骤2内容}

\`\`\`{代码语言}
{示例代码2}
\`\`\`

### 步骤3：{步骤3标题}
{步骤3内容}

## 最佳实践
{最佳实践内容}

## 常见问题
**Q: {问题1}**
A: {答案1}

**Q: {问题2}**
A: {答案2}

## 总结
{总结内容}

## 参考资料
- {参考1}
- {参考2}

---
作者：{作者名}
日期：{发布日期}`,
    variables: [
      { name: '文章标题', description: '文章标题', type: 'text', required: true },
      { name: '引言内容', description: '开篇引言', type: 'textarea', required: true },
      { name: '主题', description: '文章主题', type: 'text', required: true },
      { name: '概念介绍', description: '概念说明', type: 'textarea', required: true },
      { name: '必要性说明', description: '为什么重要', type: 'textarea', required: true },
      { name: '步骤1标题', description: '步骤1标题', type: 'text', required: true },
      { name: '步骤1内容', description: '步骤1详细内容', type: 'textarea', required: true },
      { name: '代码语言', description: '代码语言', type: 'text', required: false, defaultValue: 'javascript' },
      { name: '示例代码1', description: '示例代码1', type: 'textarea', required: false },
      { name: '步骤2标题', description: '步骤2标题', type: 'text', required: true },
      { name: '步骤2内容', description: '步骤2详细内容', type: 'textarea', required: true },
      { name: '示例代码2', description: '示例代码2', type: 'textarea', required: false },
      { name: '步骤3标题', description: '步骤3标题', type: 'text', required: true },
      { name: '步骤3内容', description: '步骤3详细内容', type: 'textarea', required: true },
      { name: '最佳实践内容', description: '最佳实践', type: 'textarea', required: true },
      { name: '问题1', description: '常见问题1', type: 'text', required: false },
      { name: '答案1', description: '答案1', type: 'textarea', required: false },
      { name: '问题2', description: '常见问题2', type: 'text', required: false },
      { name: '答案2', description: '答案2', type: 'textarea', required: false },
      { name: '总结内容', description: '文章总结', type: 'textarea', required: true },
      { name: '参考1', description: '参考资料1', type: 'text', required: false },
      { name: '参考2', description: '参考资料2', type: 'text', required: false },
      { name: '作者名', description: '作者署名', type: 'text', required: true },
      { name: '发布日期', description: '发布日期', type: 'date', required: true }
    ],
    tags: ['技术', '博客', '教程'],
    isPublic: true,
    language: 'zh',
    usageCount: 234,
    createdAt: '2024-01-03T00:00:00Z'
  }
];

export const useTemplateStore = create<TemplateStore>()(
  persist(
    (set, get) => ({
      // 初始状态
      templates: DEFAULT_TEMPLATES,
      myTemplates: [],
      publicTemplates: DEFAULT_TEMPLATES,
      favoriteTemplates: [],
      recentTemplates: [],
      loading: false,
      error: null,
      searchQuery: '',
      selectedCategory: 'all',

      // 加载所有模板
      loadTemplates: async () => {
        set({ loading: true, error: null });
        try {
          // 尝试从后端加载模板
          const response = await templateService.getTemplates();
          set({ 
            templates: [...DEFAULT_TEMPLATES, ...response],
            publicTemplates: [...DEFAULT_TEMPLATES, ...response.filter(t => t.isPublic)],
            loading: false 
          });
        } catch (error) {
          // 如果后端服务不可用，使用默认模板
          console.log('使用默认模板');
          set({ 
            templates: DEFAULT_TEMPLATES,
            publicTemplates: DEFAULT_TEMPLATES,
            loading: false 
          });
        }
      },

      // 加载我的模板
      loadMyTemplates: async () => {
        set({ loading: true });
        try {
          const response = await templateService.getMyTemplates();
          set({ myTemplates: response, loading: false });
        } catch (error) {
          set({ error: '加载模板失败', loading: false });
        }
      },

      // 加载公共模板
      loadPublicTemplates: async () => {
        set({ loading: true });
        try {
          const response = await templateService.getPublicTemplates();
          set({ 
            publicTemplates: [...DEFAULT_TEMPLATES, ...response],
            loading: false 
          });
        } catch (error) {
          set({ 
            publicTemplates: DEFAULT_TEMPLATES,
            loading: false 
          });
        }
      },

      // 搜索模板
      searchTemplates: async (query: string) => {
        set({ searchQuery: query });
        if (!query) {
          get().loadTemplates();
          return;
        }
        
        const filtered = get().templates.filter(t => 
          t.name.includes(query) || 
          t.description?.includes(query) ||
          t.tags?.some(tag => tag.includes(query))
        );
        set({ templates: filtered });
      },

      // 根据ID获取模板
      getTemplateById: (id: string) => {
        return get().templates.find(t => t.id === id);
      },

      // 创建模板
      createTemplate: async (template: Partial<Template>) => {
        const newTemplate: Template = {
          id: `template_${Date.now()}`,
          name: template.name || '新模板',
          description: template.description,
          category: template.category || 'other',
          content: template.content || '',
          variables: template.variables || [],
          tags: template.tags || [],
          isPublic: template.isPublic ?? false,
          language: template.language || 'zh',
          usageCount: 0,
          createdAt: new Date().toISOString(),
          ...template
        };

        try {
          const created = await templateService.createTemplate(newTemplate);
          set(state => ({
            templates: [...state.templates, created],
            myTemplates: [...state.myTemplates, created]
          }));
          message.success('模板创建成功');
          return created;
        } catch (error) {
          // 如果后端不可用，仅在本地存储
          set(state => ({
            templates: [...state.templates, newTemplate],
            myTemplates: [...state.myTemplates, newTemplate]
          }));
          message.success('模板已保存到本地');
          return newTemplate;
        }
      },

      // 更新模板
      updateTemplate: async (id: string, updates: Partial<Template>) => {
        try {
          await templateService.updateTemplate(id, updates);
          set(state => ({
            templates: state.templates.map(t => 
              t.id === id ? { ...t, ...updates, updatedAt: new Date().toISOString() } : t
            ),
            myTemplates: state.myTemplates.map(t => 
              t.id === id ? { ...t, ...updates, updatedAt: new Date().toISOString() } : t
            )
          }));
          message.success('模板更新成功');
        } catch (error) {
          // 仅在本地更新
          set(state => ({
            templates: state.templates.map(t => 
              t.id === id ? { ...t, ...updates, updatedAt: new Date().toISOString() } : t
            ),
            myTemplates: state.myTemplates.map(t => 
              t.id === id ? { ...t, ...updates, updatedAt: new Date().toISOString() } : t
            )
          }));
          message.success('模板已在本地更新');
        }
      },

      // 删除模板
      deleteTemplate: async (id: string) => {
        // 不允许删除默认模板
        if (id.startsWith('default_')) {
          message.error('默认模板不能删除');
          return;
        }

        try {
          await templateService.deleteTemplate(id);
          set(state => ({
            templates: state.templates.filter(t => t.id !== id),
            myTemplates: state.myTemplates.filter(t => t.id !== id),
            favoriteTemplates: state.favoriteTemplates.filter(fId => fId !== id),
            recentTemplates: state.recentTemplates.filter(rId => rId !== id)
          }));
          message.success('模板删除成功');
        } catch (error) {
          // 仅在本地删除
          set(state => ({
            templates: state.templates.filter(t => t.id !== id),
            myTemplates: state.myTemplates.filter(t => t.id !== id),
            favoriteTemplates: state.favoriteTemplates.filter(fId => fId !== id),
            recentTemplates: state.recentTemplates.filter(rId => rId !== id)
          }));
          message.success('模板已从本地删除');
        }
      },

      // 复制模板
      duplicateTemplate: async (id: string) => {
        const original = get().getTemplateById(id);
        if (!original) {
          message.error('模板不存在');
          throw new Error('Template not found');
        }

        const duplicate = {
          ...original,
          id: `template_${Date.now()}`,
          name: `${original.name} (副本)`,
          createdAt: new Date().toISOString(),
          usageCount: 0
        };

        return get().createTemplate(duplicate);
      },

      // 切换收藏
      toggleFavorite: (templateId: string) => {
        set(state => {
          const isFavorite = state.favoriteTemplates.includes(templateId);
          return {
            favoriteTemplates: isFavorite 
              ? state.favoriteTemplates.filter(id => id !== templateId)
              : [...state.favoriteTemplates, templateId]
          };
        });
      },

      // 添加到最近使用
      addToRecent: (templateId: string) => {
        set(state => {
          const filtered = state.recentTemplates.filter(id => id !== templateId);
          return {
            recentTemplates: [templateId, ...filtered].slice(0, 10) // 最多保留10个
          };
        });
      },

      // 清空最近使用
      clearRecentTemplates: () => {
        set({ recentTemplates: [] });
      },

      // 增加使用次数
      incrementUsageCount: (templateId: string) => {
        set(state => ({
          templates: state.templates.map(t => 
            t.id === templateId 
              ? { ...t, usageCount: t.usageCount + 1, lastUsedAt: new Date().toISOString() }
              : t
          )
        }));
        get().addToRecent(templateId);
      },

      // 导入模板
      importTemplate: async (templateData: any) => {
        const imported = {
          ...templateData,
          id: `template_${Date.now()}`,
          createdAt: new Date().toISOString(),
          usageCount: 0
        };
        return get().createTemplate(imported);
      },

      // 导出模板
      exportTemplate: async (templateId: string) => {
        const template = get().getTemplateById(templateId);
        if (!template) {
          throw new Error('Template not found');
        }
        
        const exported = { ...template };
        delete (exported as any).id;
        delete (exported as any).createdAt;
        delete (exported as any).updatedAt;
        delete (exported as any).usageCount;
        delete (exported as any).lastUsedAt;
        
        return exported;
      },

      // 应用模板
      applyTemplate: (templateId: string, variables: Record<string, any>) => {
        const template = get().getTemplateById(templateId);
        if (!template) {
          throw new Error('Template not found');
        }

        let content = template.content;
        
        // 替换变量
        Object.entries(variables).forEach(([key, value]) => {
          const regex = new RegExp(`\\{${key}\\}`, 'g');
          content = content.replace(regex, value || '');
        });

        // 增加使用次数
        get().incrementUsageCount(templateId);

        return content;
      },

      // 设置搜索查询
      setSearchQuery: (query: string) => {
        set({ searchQuery: query });
      },

      // 设置选中分类
      setSelectedCategory: (category: string) => {
        set({ selectedCategory: category });
      }
    }),
    {
      name: 'template-store',
      partialize: (state) => ({
        favoriteTemplates: state.favoriteTemplates,
        recentTemplates: state.recentTemplates,
        myTemplates: state.myTemplates
      })
    }
  )
);